<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
</head>

<body>
  <div class="addBrand-container" id="member-add-app">
    <div class="container">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" :inline="false" label-width="180px"
        class="demo-ruleForm">
        <el-form-item label="账号:" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账号" maxlength="20" />
        </el-form-item>
        <el-form-item label="员工姓名:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入员工姓名" maxlength="20" />
        </el-form-item>

        <el-form-item label="手机号:" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" maxlength="20" />
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="ruleForm.idNumber" placeholder="请输入身份证号" maxlength="20" />
        </el-form-item>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="goBack()">
              取消
            </el-button>
            <el-button type="primary" @click="submitForm('ruleForm', false)">
              保存
            </el-button>
            <el-button v-if="actionType == 'add'" type="primary" class="continue" @click="submitForm('ruleForm', true)">
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
  <!-- 开发环境版本，包含了有帮助的命令行警告 -->
  <script src="../../plugins/vue/vue.js"></script>
  <!-- 引入组件库 -->
  <script src="../../plugins/element-ui/index.js"></script>
  <!-- 引入axios -->
  <script src="../../plugins/axios/axios.min.js"></script>
  <script src="../../js/request.js"></script>
  <script src="../../api/member.js"></script>
  <script src="../../js/validate.js"></script>
  <script src="../../js/index.js"></script>
  <script>
    new Vue({
      el: '#member-add-app',
      data() {
        return {
          id: '',
          actionType: '',
          ruleForm: {
            'name': '',
            'phone': '',
            'sex': '男',
            'idNumber': '',
            username: ''
          }
        }
      },
      computed: {
        rules() {
          return {
            //账号
            username: [
              {
                required: true,
                validator: (rule, value, callback) => {
                  if (!value) {
                    callback(new Error('请输入账号'))
                  } else if (value.length > 20 || value.length < 3) {
                    callback(new Error('账号长度应是3-20'))
                  } else {
                    callback()
                  }
                },
                trigger: 'blur'
              }
            ],
            //姓名
            name: [{
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error('请输入姓名'))
                } else if (value.length > 12) {
                  callback(new Error('姓名长度应是1-12'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }],
            'phone': [{
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error('请输入手机号'))
                } else if (!/^1(3|4|5|6|7|8)\d{9}$/.test(value)) {
                  callback(new Error('请输入正确的手机号!'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }],
            'idNumber': [{
              required: true,
              validator: (rule, value, callback) => {
                if (!value) {
                  callback(new Error('请输入身份证号码'))
                } else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
                  callback(new Error('身份证号码不正确'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }]
          }
        }
      },
      created() {
        // 使用URLSearchParams解析URL参数，支持编码的ID
        const urlParams = new URLSearchParams(location.search)
        this.id = urlParams.get('id')

        console.log('=== 调试信息开始 ===')
        console.log('created - 获取到的ID:', this.id)
        console.log('created - ID类型:', typeof this.id)
        console.log('created - 当前URL:', location.href)

        // 对比两种解析方法
        const oldMethod = requestUrlParam('id')
        console.log('created - 旧方法解析结果:', oldMethod)
        console.log('created - 新方法解析结果:', this.id)

        // 如果ID为空，尝试从URL中直接提取
        if (!this.id) {
          const url = location.href
          const match = url.match(/[?&]id=([^&]+)/)
          if (match) {
            this.id = decodeURIComponent(match[1])
            console.log('created - 从URL直接提取的ID:', this.id)
          }
        }

        this.actionType = this.id ? 'edit' : 'add'
        console.log('created - 操作类型:', this.actionType)

        if (this.id) {
          // 确保ID是字符串类型，避免大数字精度丢失
          this.id = String(this.id)
          console.log('created - 最终ID:', this.id)
          console.log('created - 准备调用init方法')
          this.init()
        } else {
          console.log('created - ID为空，跳过init调用')
        }
        console.log('=== 调试信息结束 ===')
      },
      mounted() {
      },
      methods: {
        async init() {
          console.log('=== init方法开始 ===')
          console.log('init - 员工ID:', this.id)
          console.log('init - 员工ID类型:', typeof this.id)

          if (!this.id) {
            console.log('init - 员工ID为空，无法查询')
            this.$message.error('员工ID不能为空')
            return
          }

          // 先测试API是否可达
          console.log('init - 准备调用API: /employee/' + this.id)

          try {
            const res = await queryEmployeeById(this.id)
            console.log('init - API响应:', res)
            console.log('init - 响应类型:', typeof res)
            console.log('init - 响应码:', res.code)
            console.log('init - 响应消息:', res.msg)
            console.log('init - 响应数据:', res.data)

            if (String(res.code) === '1' && res.data) {
              console.log('init - 查询成功，员工数据:', res.data)
              this.ruleForm = { ...res.data }
              this.ruleForm.sex = res.data.sex === '0' ? '女' : '男'
              console.log('init - 表单数据已填充:', this.ruleForm)
            } else {
              console.log('init - 查询失败，响应码:', res.code, '消息:', res.msg)
              this.$message.error(res.msg || '员工不存在')
            }
          } catch (err) {
            console.log('init - 请求错误:', err)
            console.log('init - 错误详情:', err.message)
            this.$message.error('请求出错了：' + err.message)
          }
          console.log('=== init方法结束 ===')
        },
        submitForm(formName, st) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.actionType === 'add') {
                const params = {
                  ...this.ruleForm,
                  sex: this.ruleForm.sex === '女' ? '0' : '1'
                }
                addEmployee(params).then(res => {
                  if (res.code === 1) {
                    this.$message.success('员工添加成功！')
                    if (!st) {
                      this.goBack()
                    } else {
                      this.ruleForm = {
                        username: '',
                        'name': '',
                        'phone': '',
                        // 'password': '',
                        // 'rePassword': '',/
                        'sex': '男',
                        'idNumber': ''
                      }
                    }
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              } else {
                const params = {
                  ...this.ruleForm,
                  id: this.id,  // 添加员工ID
                  sex: this.ruleForm.sex === '女' ? '0' : '1'
                }
                editEmployee(params).then(res => {
                  if (res.code === 1) {
                    this.$message.success('员工信息修改成功！')
                    this.goBack()
                  } else {
                    this.$message.error(res.msg || '操作失败')
                  }
                }).catch(err => {
                  this.$message.error('请求出错了：' + err)
                })
              }
            } else {
              console.log('error submit!!')
              return false
            }
          })
        },
        goBack() {
          window.parent.menuHandle({
            id: '2',
            url: '/backend/page/member/list.html',
            name: '员工管理'
          }, false)
        }
      }
    })
  </script>
</body>

</html>